<template>
  <div class="container">
    <Breadcrumb :items="['充电站管理', '汽车充电站点']" />
    <a-card class="general-card" :title="$t('汽车充电站点')">
      <div class="search-area">
        <a-form
          :model="searchForm"
          label-align="left"
          :label-col-props="{ span: 5 }"
          :wrapper-col-props="{ span: 19 }"
          label-layout="inline"
          class="search-form"
        >
          <a-row :gutter="24">
            <a-col :span="7">
              <a-form-item field="name" :label="$t('站点名称')">
                <a-input
                  v-model="searchForm.name"
                  :placeholder="$t('请输入站点名称')"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="7">
              <a-form-item field="areaCode" :label="$t('地区名称')">
                <a-input
                  v-model="searchForm.areaCode"
                  :placeholder="$t('请输入地区名称')"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="7" v-if="userInfo.role === 'admin'">
              <a-form-item field="partnerId" :label="$t('关联合伙人')">
                <a-select
                  v-model="searchForm.partnerId"
                  :placeholder="$t('请选择合伙人')"
                  allow-clear
                  :loading="partnerLoading"
                  class="search-select"
                >
                  <a-option
                    v-for="partner in partnerOptions"
                    :key="partner.id"
                    :value="partner.id"
                  >
                    {{ partner.partnerName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <div class="operation-area">
          <div class="search-buttons">
            <a-button class="search-btn" type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('搜索') }}
            </a-button>
            <a-button class="reset-btn" @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('重置') }}
            </a-button>
          </div>

          <a-divider
            style="height: 24px; margin: 0 16px"
            direction="vertical"
          />

          <div class="add-button">
            <a-button type="primary" class="add-btn" @click="openAddDialog">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('新增') }}
            </a-button>
          </div>
        </div>
      </div>
      <a-divider style="margin-top: 0; margin-bottom: 16px" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="站点名称" data-index="name" />
          <a-table-column title="详细地址" data-index="address" />
          <a-table-column title="站点类型" data-index="chargingGroupType">
            <template #cell>
              <a-tag color="green">汽车</a-tag>
            </template>
          </a-table-column>
          <!-- <a-table-column title="分成模式" data-index="propType">
            <template #cell="{ record }">
              <span>{{ getPropTypeText(record.propType) }}</span>
            </template>
          </a-table-column> -->
          <a-table-column title="客服电话" data-index="servicePhone" />
          <a-table-column title="创建时间" data-index="createDate">
            <template #cell="{ record }">
              {{ formatDateTime(record.createDate) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="180">
            <template #cell="{ record }">
              <a-button
                type="text"
                size="small"
                @click="openEditDialog(record)"
              >
                编辑
              </a-button>
              <a-divider direction="vertical" />
              <a-button type="text" size="small" @click="viewDevices(record)">
                查看设备
              </a-button>
              <a-divider direction="vertical" />
              <a-button type="text" size="small" @click="exportQrCodes(record)">
                导出二维码
              </a-button>
              <a-divider direction="vertical" />
              <a-popconfirm
                content="确定要删除此站点吗？"
                @ok="handleDelete(record)"
              >
                <a-button type="text" status="danger" size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑对话框 -->
    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑汽车充电站点' : '新增汽车充电站点'"
      @before-ok="handleSubmit"
      @cancel="
        () => {
          visible = false;
        }
      "
      width="800px"
      :footer="false"
      class="station-modal"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="left"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        class="station-form"
      >
        <a-card title="基本信息" class="form-card">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="name" label="站点名称" required>
                <a-input v-model="form.name" placeholder="请输入站点名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="servicePhone" label="客服电话">
                <a-input
                  v-model="form.servicePhone"
                  placeholder="请输入客服电话"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="partnerId" label="关联合伙人">
                <a-select
                  v-model="form.partnerId"
                  placeholder="请选择合伙人"
                  allow-clear
                  :loading="partnerSelectLoading"
                >
                  <a-option
                    v-for="partner in partnerSelectOptions"
                    :key="partner.id"
                    :value="partner.id"
                  >
                    {{ partner.partnerName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card title="计费设置" class="form-card">
          <a-divider style="margin: 16px 0">四时段电费设置</a-divider>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="topTimeAmount" label="尖时段电费">
                <a-input-number
                  v-model="form.carBillingMethod.elecPriceSetting.topTimeAmount"
                  placeholder="请输入尖时段电费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) => handleAmountChange('topTimeAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="topTimeServiceAmount" label="尖段服务费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting.topTimeServiceAmount
                  "
                  placeholder="请输入尖时段服务费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) => handleAmountChange('topTimeServiceAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="peakTimeAmount" label="峰时段电费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting.peakTimeAmount
                  "
                  placeholder="请输入峰时段电费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) => handleAmountChange('peakTimeAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="peakTimeServiceAmount" label="峰段服务费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting.peakTimeServiceAmount
                  "
                  placeholder="请输入峰时段服务费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) =>
                      handleAmountChange('peakTimeServiceAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="normalTimeAmount" label="平时段电费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting.normalTimeAmount
                  "
                  placeholder="请输入平时段电费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) => handleAmountChange('normalTimeAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="normalTimeServiceAmount" label="平段服务费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting
                      .normalTimeServiceAmount
                  "
                  placeholder="请输入平时段服务费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) =>
                      handleAmountChange('normalTimeServiceAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="valleyTimeAmount" label="谷时段电费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting.valleyTimeAmount
                  "
                  placeholder="请输入谷时段电费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) => handleAmountChange('valleyTimeAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="valleyTimeServiceAmount" label="谷段服务费">
                <a-input-number
                  v-model="
                    form.carBillingMethod.elecPriceSetting
                      .valleyTimeServiceAmount
                  "
                  placeholder="请输入谷时段服务费"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                  @change="
                    (value) =>
                      handleAmountChange('valleyTimeServiceAmount', value)
                  "
                >
                  <template #append>元/度</template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>

          <a-divider style="margin: 16px 0">时段设置（手动设置）</a-divider>

          <a-form-item field="timePeriodSetting" label="时段设置">
            <div class="time-period-container">
              <div class="time-period-header">
                <div class="time-period-label">时间段</div>
                <div class="time-period-label">时段类型</div>
                <div class="time-period-label">操作</div>
              </div>
              <div
                v-for="(item, index) in timePeriods"
                :key="index"
                class="time-period-item"
              >
                <div class="time-period-time">
                  <a-time-picker
                    v-model="item.startTime"
                    format="HH:mm"
                    size="small"
                    style="width: 90px"
                    :step="{ minute: 30 }"
                    @change="validateTimeRanges"
                  />
                  <span class="time-separator">至</span>
                  <a-time-picker
                    v-model="item.endTime"
                    format="HH:mm"
                    size="small"
                    style="width: 90px"
                    :step="{ minute: 30 }"
                    @change="validateTimeRanges"
                    v-if="item.endTime !== '24:00'"
                  />
                  <span
                    v-else
                    style="
                      width: 90px;
                      display: inline-block;
                      text-align: center;
                      line-height: 24px;
                      border: 1px solid var(--color-border);
                      border-radius: 2px;
                      padding: 0 8px;
                      font-size: 14px;
                    "
                    >24:00</span
                  >
                </div>
                <div class="time-period-type">
                  <a-radio-group
                    v-model="item.type"
                    type="button"
                    size="small"
                    @change="updateTimePeriodSettings"
                  >
                    <a-radio :value="0">尖</a-radio>
                    <a-radio :value="1">峰</a-radio>
                    <a-radio :value="2">平</a-radio>
                    <a-radio :value="3">谷</a-radio>
                  </a-radio-group>
                  <div class="time-period-price">
                    <template v-if="item.type === 0">
                      <span
                        >电费:{{ getAmountByTimeType(0) }}元 服务费:{{
                          getServiceAmountByTimeType(0)
                        }}元</span
                      >
                    </template>
                    <template v-else-if="item.type === 1">
                      <span
                        >电费:{{ getAmountByTimeType(1) }}元 服务费:{{
                          getServiceAmountByTimeType(1)
                        }}元</span
                      >
                    </template>
                    <template v-else-if="item.type === 2">
                      <span
                        >电费:{{ getAmountByTimeType(2) }}元 服务费:{{
                          getServiceAmountByTimeType(2)
                        }}元</span
                      >
                    </template>
                    <template v-else-if="item.type === 3">
                      <span
                        >电费:{{ getAmountByTimeType(3) }}元 服务费:{{
                          getServiceAmountByTimeType(3)
                        }}元</span
                      >
                    </template>
                  </div>
                </div>
                <div class="time-period-actions">
                  <a-button
                    size="mini"
                    status="danger"
                    @click="removeTimePeriod(index)"
                    :disabled="timePeriods.length <= 1"
                  >
                    <template #icon><icon-delete /></template>
                  </a-button>
                </div>
              </div>
              <div class="add-time-period">
                <a-button long type="dashed" @click="addTimePeriod">
                  <template #icon><icon-plus /></template>
                  添加时段
                </a-button>
              </div>
            </div>
          </a-form-item>

          <a-divider style="margin: 16px 0">收费方式设置</a-divider>

          <a-form-item field="billingConfigs" label="金额选择项">
            <div class="billing-config-list">
              <div class="billing-values-container">
                <a-space wrap :size="16">
                  <a-button
                    v-for="(item, index) in form.carChargingMethod.values"
                    :key="index"
                    :type="isItemSelected(item) ? 'primary' : 'outline'"
                    @click="toggleBillingSelection(index)"
                  >
                    {{ getItemValueUnit(item) }}
                    <template #icon>
                      <icon-close
                        style="margin-left: 4px; font-size: 12px"
                        @click.stop="removeBillingConfig(index)"
                      />
                    </template>
                  </a-button>
                  <a-button type="dashed" @click="addBillingConfig">
                    <template #icon><icon-plus /></template>
                    添加金额
                  </a-button>
                </a-space>
              </div>

              <div class="custom-value-input" style="margin-top: 16px">
                <a-input-number
                  v-model="customValue"
                  placeholder="请输入自定义金额"
                  :precision="2"
                  :min="0"
                  style="width: 200px"
                >
                  <template #append>元</template>
                </a-input-number>
                <a-button
                  type="primary"
                  @click="addCustomValue"
                  style="margin-left: 16px"
                >
                  添加
                </a-button>
              </div>
            </div>
          </a-form-item>
        </a-card>

        <a-card title="地理位置" class="form-card location-card">
          <a-form-item field="province" label="所在省份" required>
            <a-select
              v-model="form.province"
              placeholder="请选择省份"
              @change="handleFormProvinceChange"
            >
              <a-option
                v-for="item in provinceOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="city" label="所在城市" required>
            <a-select
              v-model="form.city"
              placeholder="请选择城市"
              :disabled="!form.province"
              @change="handleFormCityChange"
            >
              <a-option
                v-for="item in formCityOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="district" label="所在区县">
            <a-select
              v-model="form.district"
              placeholder="请选择区县"
              :disabled="!form.city"
              allow-clear
            >
              <a-option
                v-for="item in districtOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item
            field="address"
            label="详细地址"
            required
            class="address-item"
          >
            <a-input
              v-model="form.address"
              placeholder="请输入详细地址"
              @input="(value: string) => debounceSearchAddress(value)"
            />
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" @click="searchAddress">
                <template #icon>
                  <icon-search />
                </template>
                定位
              </a-button>
              <a-button
                @click="
                  () => {
                    if (!form.address) {
                      Message.warning('请先输入详细地址');
                      return;
                    }

                    // 构建完整地址
                    let fullAddress = '';
                    if (form.province) {
                      fullAddress += form.province;
                    }
                    if (form.city) {
                      fullAddress += form.city;
                    }
                    if (form.district) {
                      fullAddress += form.district;
                    }
                    fullAddress += form.address;

                    tryAlternativeSearch(fullAddress);
                  }
                "
              >
                <template #icon>
                  <icon-refresh />
                </template>
                备选定位
              </a-button>
              <a-button @click="openCoordinatePicker">
                <template #icon>
                  <icon-edit />
                </template>
                手动选点
              </a-button>
              <a-button @click="inputCoordinates">
                <template #icon>
                  <icon-code />
                </template>
                输入坐标
              </a-button>
              <a-tooltip>
                <template #content>
                  <div style="max-width: 300px">
                    <p><b>定位</b>：使用高德地图API根据地址查询经纬度</p>
                    <p
                      ><b>备选定位</b
                      >：当主定位方式失败时使用，通过JSONP方式请求</p
                    >
                    <p
                      ><b>手动选点</b
                      >：打开高德地图坐标拾取器，手动选择位置并复制经纬度</p
                    >
                    <p
                      ><b>输入坐标</b>：直接输入经纬度坐标（格式：经度,纬度）</p
                    >
                  </div>
                </template>
                <icon-question-circle />
              </a-tooltip>
            </a-space>
          </a-form-item>

          <a-form-item field="location" label="地理位置">
            <div class="map-container">
              <div id="map-container" style="height: 300px"></div>
              <div class="map-info">
                <p>经度：{{ form.changingGroupLon }}</p>
                <p>纬度：{{ form.chargingGroupLat }}</p>
                <p class="map-tip">提示：点击地图选择位置</p>
              </div>
            </div>
            <!-- 地图加载失败时的备用输入框 -->
            <div v-if="!AMap" class="manual-location-input">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="changingGroupLon" label="经度">
                    <a-input-number
                      v-model="form.changingGroupLon"
                      placeholder="请输入经度"
                      :precision="6"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="chargingGroupLat" label="纬度">
                    <a-input-number
                      v-model="form.chargingGroupLat"
                      placeholder="请输入纬度"
                      :precision="6"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-alert type="warning">
                <template #message>
                  高德地图加载失败，请手动输入经纬度。您可以通过以下方式获取经纬度：
                  <ol>
                    <li
                      >访问
                      <a
                        href="https://lbs.amap.com/tools/picker"
                        target="_blank"
                        >高德坐标拾取器</a
                      ></li
                    >
                    <li>在地图上选择位置，复制经纬度</li>
                    <li>将经度和纬度分别填入上方输入框</li>
                  </ol>
                </template>
              </a-alert>
            </div>
          </a-form-item>
        </a-card>

        <a-card title="站点图片" class="form-card">
          <a-form-item field="siteImages" label="站点图片">
            <a-upload
              action="/api/file/upload"
              :file-list="fileList"
              image-preview
              list-type="picture-card"
              @success="handleUploadSuccess"
              @remove="handleRemove"
            >
              <template #upload-button>
                <div>
                  <icon-plus />
                  <div style="margin-top: 10px">上传</div>
                </div>
              </template>
            </a-upload>
          </a-form-item>
        </a-card>

        <a-card title="描述信息" class="form-card">
          <a-form-item field="siteDescription" label="站点描述">
            <a-textarea
              v-model="form.siteDescription"
              placeholder="请输入站点描述"
            />
          </a-form-item>
        </a-card>

        <div class="form-footer">
          <a-space>
            <a-button @click="visible = false">取消</a-button>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import {
    ref,
    reactive,
    computed,
    onMounted,
    onBeforeUnmount,
    nextTick,
  } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store';
  import {
    getCarChargingGroupLabelList,
    listCarChargingGroups,
    getCarChargingGroupInfo,
    addCarChargingGroup,
    updateCarChargingGroup,
    CarChargingGroupDetailVo,
    CarGroupLabelConfig,
    AddCarChargingGroupReq,
    deleteCarChargingGroup,
    getChargingGroupQrCodes,
  } from '@/api/car-charging-group';
  import { getAllPartners } from '@/api/partner';
  import { getProvinces, getCities, getDistricts, Region } from '@/api/region';
  import JSZip from 'jszip';
  import QRCode from 'qrcode';

  // 获取用户信息
  const userInfo = useUserStore();
  const router = useRouter();
  const { loading, setLoading } = useLoading();

  // 防抖函数
  function debounce<T extends (...args: any[]) => any>(
    fn: T,
    delay: number
  ): (...args: Parameters<T>) => void {
    let timer: number | null = null;
    return function (this: any, ...args: Parameters<T>): void {
      if (timer) {
        clearTimeout(timer);
      }
      timer = window.setTimeout(() => {
        fn.apply(this, args);
        timer = null;
      }, delay);
    };
  }

  // 声明 AMap 类型
  declare global {
    interface Window {
      AMap: any;
      _AMapSecurityConfig: {
        securityJsCode: string;
        serviceHost: string;
      };
    }
  }

  // 高德地图 API 配置
  const AMAP_CONFIG = {
    // 不使用代理服务器
    useProxy: false,
    // 在此处填写您的高德地图 API Key
    key: 'f8b1e8b95e3a514872f912930c9bc21d',
    // 安全密钥（新版本必须配置）
    securityJsCode: '0d5c3b1281576b6f334303936a4ba65d',
    // 使用与安全密钥脚本相同的版本
    version: '2.0',
    plugins: ['AMap.Geocoder', 'AMap.PlaceSearch'],
  };

  // 加载高德地图脚本
  let AMap: any = null;
  let map: any = null;
  let marker: any = null;
  let geocoder: any = null;

  // 表格数据
  const renderData = ref<CarChargingGroupDetailVo[]>([]);
  const visible = ref(false);
  const isEdit = ref(false);
  const formRef = ref();
  const fileList = ref([]);
  const labelOptions = ref<CarGroupLabelConfig[]>([]);

  // 生成24小时分段（每半小时一段）
  interface TimePeriod {
    startTime: string;
    endTime: string;
    type: number; // 1: 尖, 2: 平, 3: 谷
  }

  const timePeriods = ref<TimePeriod[]>([]);
  const timeRangesValid = ref(true);
  const timeRangeErrorMessage = ref('');

  // 省市区选项
  const provinceOptions = ref<{ label: string; value: string }[]>([]);
  const formCityOptions = ref<{ label: string; value: string }[]>([]);
  const districtOptions = ref<{ label: string; value: string }[]>([]);

  // 存储省市区ID映射
  const provinceMap = ref<Map<string, number>>(new Map());
  const cityMap = ref<Map<string, number>>(new Map());

  // 搜索表单
  const searchForm = reactive({
    name: '',
    areaCode: '',
    chargingGroupType: 1, // 固定为汽车类型
    partnerId: undefined as number | undefined,
  });

  // 合伙人选择数据（用于表单中的合伙人选择）
  const partnerSelectLoading = ref(false);
  const partnerSelectOptions = ref<{ id: number; partnerName: string }[]>([]);

  // 新增/编辑表单
  const formInitialState: Partial<CarChargingGroupDetailVo> = {
    name: '',
    address: '',
    areaCode: '',
    chargingGroupType: 1, // 固定为汽车类型
    chargingGroupLat: '',
    changingGroupLon: '',
    siteImages: '',
    siteDescription: '',
    parkDescription: '',
    servicePhone: '',
    propType: 0,
    carGroupLabels: [],
    province: '',
    city: '',
    district: '',
    labelIds: [],
    partnerId: undefined,
    carBillingMethod: {
      elecPriceSetting: {
        topTimeAmount: '0',
        peakTimeAmount: '0',
        normalTimeAmount: '0',
        valleyTimeAmount: '0',
        serviceAmount: '0',
        topTimeServiceAmount: '0',
        peakTimeServiceAmount: '0',
        normalTimeServiceAmount: '0',
        valleyTimeServiceAmount: '0',
      },
      intervalSettingList: [],
    },
    carChargingMethod: {
      isFullStop: 0,
      values: [
        {
          billingType: 1,
          billingName: '10元',
          billingValue: '10',
          isSelect: 1, // 默认选中第一个
        },
        {
          billingType: 1,
          billingName: '20元',
          billingValue: '20',
          isSelect: 0,
        },
        {
          billingType: 1,
          billingName: '30元',
          billingValue: '30',
          isSelect: 0,
        },
        {
          billingType: 1,
          billingName: '40元',
          billingValue: '40',
          isSelect: 0,
        },
        {
          billingType: 1,
          billingName: '50元',
          billingValue: '50',
          isSelect: 0,
        },
        {
          billingType: 2,
          billingName: '自定义',
          billingValue: '自定义',
          isSelect: 0,
        },
      ],
    },
  };

  const form = reactive<Partial<CarChargingGroupDetailVo>>({
    ...formInitialState,
  });

  // 分页
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入站点名称' }],
    address: [{ required: true, message: '请输入详细地址' }],
    changingGroupLon: [{ required: true, message: '请输入经度' }],
    chargingGroupLat: [{ required: true, message: '请输入纬度' }],
  };

  // 客户相关数据
  const partnerLoading = ref(false);
  const partnerOptions = ref<{ id: number; partnerName: string }[]>([]);

  // 格式化日期时间
  function formatDateTime(dateTime: any): string {
    if (!dateTime) return '';

    // 如果是字符串类型，尝试直接格式化
    if (typeof dateTime === 'string') {
      try {
        return dateTime.substring(0, 19).replace('T', ' ');
      } catch (error) {
        console.error('格式化日期字符串出错:', error);
        return dateTime;
      }
    }

    // 如果是Date类型，转换为标准格式
    if (dateTime instanceof Date) {
      try {
        return dateTime.toISOString().substring(0, 19).replace('T', ' ');
      } catch (error) {
        console.error('格式化Date对象出错:', error);
        return dateTime.toString();
      }
    }

    // 如果是数字类型（时间戳），转换为日期
    if (typeof dateTime === 'number') {
      try {
        const date = new Date(dateTime);
        return date.toISOString().substring(0, 19).replace('T', ' ');
      } catch (error) {
        console.error('格式化时间戳出错:', error);
        return dateTime.toString();
      }
    }

    // 其他类型，返回原始值的字符串表示
    return String(dateTime);
  }

  // 获取分成模式文本
  function getPropTypeText(type?: number) {
    switch (type) {
      case 0:
        return '按比例分成';
      case 1:
        return '固定金额分成';
      default:
        return '未设置';
    }
  }

  // 处理文件上传成功
  function handleUploadSuccess(file: any, fileList: any[]) {
    if (file.response && file.response.data) {
      form.siteImages = file.response.data.url;
    }
  }

  // 处理移除文件
  function handleRemove(file: any) {
    form.siteImages = '';
  }

  // 获取汽车充电站点列表
  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        pageNum: pagination.current,
        size: pagination.pageSize,
        name: searchForm.name || undefined,
        areaCode: searchForm.areaCode || undefined,
        chargingGroupType: searchForm.chargingGroupType,
        partnerId: searchForm.partnerId,
      };
      console.log('站点查询参数params', params);
      const res: any = await listCarChargingGroups(params);
      if (res.code === 200 && res.data) {
        console.log('res', res);
        renderData.value = res.data.records || [];
        pagination.total = res.data.total || 0;
        pagination.current = res.data.current || 1;
        pagination.pageSize = res.data.size || 10;
      } else {
        Message.error(
          `获取汽车充电站点列表失败: ${res?.message || '未知错误'}`
        );
      }
    } catch (err) {
      console.error('获取汽车充电站点列表异常:', err);
      Message.error('获取汽车充电站点列表失败');
    } finally {
      setLoading(false);
    }
  }

  // 搜索
  function search() {
    pagination.current = 1;
    fetchData();
  }

  // 重置
  function reset() {
    searchForm.name = '';
    searchForm.areaCode = '';
    searchForm.chargingGroupType = 1;
    searchForm.partnerId = undefined;
    pagination.current = 1;
    fetchData();

    // 重置金额选择项为默认值
    if (form.carChargingMethod) {
      form.carChargingMethod.values =
        formInitialState.carChargingMethod.values.map((item) => ({ ...item }));
    }
  }

  // 页码变化
  function onPageChange(current: number) {
    pagination.current = current;
    fetchData();
  }

  // 每页条数变化
  function onPageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
  }

  // 打开新增对话框
  function openAddDialog() {
    isEdit.value = false;

    // 确保carBillingMethod对象存在并且有正确的初始值
    form.carBillingMethod = {
      elecPriceSetting: {
        topTimeAmount: '0',
        peakTimeAmount: '0',
        normalTimeAmount: '0',
        valleyTimeAmount: '0',
        serviceAmount: '0',
        topTimeServiceAmount: '0',
        peakTimeServiceAmount: '0',
        normalTimeServiceAmount: '0',
        valleyTimeServiceAmount: '0',
      },
      intervalSettingList: [],
    };

    // 重置其他表单字段
    Object.assign(form, {
      ...formInitialState,
      carBillingMethod: form.carBillingMethod,
    });

    fileList.value = [];
    visible.value = true;

    // 确保省份数据已加载
    if (provinceOptions.value.length === 0) {
      loadProvinceData();
    }

    // 加载合伙人下拉框数据
    loadPartnerSelectData();

    // 等待DOM更新后初始化地图
    setTimeout(() => {
      initMap();
    }, 100);

    // 初始化时段设置
    initTimePeriods();
  }

  // 打开编辑对话框
  async function openEditDialog(record: any) {
    console.log('打开编辑对话框，记录数据:', record);
    isEdit.value = true;

    try {
      const res = await getCarChargingGroupInfo(record.id as number);
      console.log('API返回的站点详情数据:', res.data);
      console.log('API返回的计费方式数据:', res.data.carBillingMethod);
      console.log('API返回的充电方式数据:', res.data.carChargingMethod);

      if (res.code === 200) {
        // 重置表单
        resetForm();

        // 加载合作方数据
        await loadPartnerData();

        const detailData = res.data;

        // 填充表单数据前先确保计费相关对象存在
        if (typeof detailData.carBillingMethod === 'string') {
          try {
            detailData.carBillingMethod = JSON.parse(
              detailData.carBillingMethod
            );
            console.log(
              'detailData.carBillingMethod',
              detailData.carBillingMethod
            );
          } catch (e) {
            console.error('解析计费方式数据失败:', e);
            detailData.carBillingMethod = formInitialState.carBillingMethod;
          }
        }

        if (typeof detailData.carChargingMethod === 'string') {
          try {
            detailData.carChargingMethod = JSON.parse(
              detailData.carChargingMethod
            );
          } catch (e) {
            console.error('解析充电方式数据失败:', e);
            detailData.carChargingMethod = formInitialState.carChargingMethod;
          }
        }

        // 填充表单数据
        Object.assign(form, detailData);

        console.log('填充数据后的表单状态:', {
          carBillingMethod: form.carBillingMethod,
          carChargingMethod: form.carChargingMethod,
        });

        // 处理计费设置
        processBillingSettings();

        console.log('处理计费设置后的状态:', {
          carBillingMethod: form.carBillingMethod,
          timePeriods: timePeriods.value,
        });

        // 处理计费值
        processBillingValues();

        console.log('处理计费值后的状态:', {
          carChargingMethod: form.carChargingMethod,
        });

        // 处理文件列表
        if (detailData.siteImages) {
          try {
            const images = JSON.parse(detailData.siteImages);
            fileList.value = images.map((url: string) => ({
              url,
              name: url.substring(url.lastIndexOf('/') + 1),
            }));
          } catch (e) {
            console.error('解析站点图片数据失败:', e);
            fileList.value = [];
          }
        }

        // 处理省市区数据
        if (detailData.provinceId) {
          await handleCascadeData();
        }

        // 打开对话框
        visible.value = true;

        // 等待对话框打开后再初始化地图
        await nextTick();

        // 如果有经纬度，初始化地图并设置标记点
        if (detailData.changingGroupLon && detailData.chargingGroupLat) {
          const lng = parseFloat(detailData.changingGroupLon);
          const lat = parseFloat(detailData.chargingGroupLat);

          // 确保地图实例存在，最多尝试3次
          let retryCount = 0;
          while (!map && retryCount < 3) {
            await initMap();
            if (!map) {
              retryCount++;
              await new Promise((resolve) => setTimeout(resolve, 500)); // 等待500ms后重试
            }
          }

          // 设置标记点和地图中心
          if (map && marker) {
            const position = [lng, lat];
            marker.setPosition(position);
            map.setCenter(position);
            map.setZoom(15);

            // 更新表单经纬度
            form.changingGroupLon = detailData.changingGroupLon;
            form.chargingGroupLat = detailData.chargingGroupLat;

            // 尝试获取地址信息
            getAddressByLngLat({
              getLng: () => lng,
              getLat: () => lat,
            });
          } else {
            Message.warning('地图加载失败，但经纬度已保存');
          }
        }
      }
    } catch (error) {
      console.error('获取站点详情失败:', error);
      Message.error('获取站点详情失败');
    }
  }

  // 处理省市区级联数据
  async function handleCascadeData() {
    if (form.province) {
      // 加载城市列表
      try {
        const provinceId = provinceMap.value.get(form.province);
        console.log('获取省份ID:', form.province, provinceId);

        if (provinceId) {
          const res = (await getCities(provinceId)) as any;
          if (res.code === 200 && res.data) {
            formCityOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            // 更新城市ID映射
            res.data.forEach((item: Region) => {
              cityMap.value.set(item.name, item.id);
            });

            // 如果有城市，加载区县列表
            if (form.city) {
              const cityId = cityMap.value.get(form.city);
              console.log('获取城市ID:', form.city, cityId);

              if (cityId) {
                const districtRes = (await getDistricts(cityId)) as any;
                if (districtRes.code === 200 && districtRes.data) {
                  districtOptions.value = districtRes.data.map(
                    (item: Region) => ({
                      label: item.name,
                      value: item.name,
                    })
                  );
                }
              } else {
                console.warn('未找到城市对应的ID:', form.city);
                // 尝试从所有城市中查找
                const allCities = (await getCities(provinceId)) as any;
                if (allCities.code === 200 && allCities.data) {
                  const matchedCity = allCities.data.find(
                    (c: Region) => c.name === form.city
                  );
                  if (matchedCity) {
                    cityMap.value.set(matchedCity.name, matchedCity.id);
                    const districtRes = (await getDistricts(
                      matchedCity.id
                    )) as any;
                    if (districtRes.code === 200 && districtRes.data) {
                      districtOptions.value = districtRes.data.map(
                        (item: Region) => ({
                          label: item.name,
                          value: item.name,
                        })
                      );
                    }
                  }
                }
              }
            }
          }
        } else {
          console.warn('未找到省份对应的ID:', form.province);
          // 尝试重新加载省份数据
          const provinceRes = (await getProvinces()) as any;
          if (provinceRes.code === 200 && provinceRes.data) {
            provinceOptions.value = provinceRes.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            // 重新映射省份ID
            provinceRes.data.forEach((item: Region) => {
              provinceMap.value.set(item.name, item.id);
            });

            // 再次尝试获取省份ID
            const newProvinceId = provinceMap.value.get(form.province);
            if (newProvinceId) {
              const cityRes = (await getCities(newProvinceId)) as any;
              if (cityRes.code === 200 && cityRes.data) {
                formCityOptions.value = cityRes.data.map((item: Region) => ({
                  label: item.name,
                  value: item.name,
                }));
                // 更新城市ID映射
                cityRes.data.forEach((item: Region) => {
                  cityMap.value.set(item.name, item.id);
                });

                // 如果有城市，加载区县列表
                if (form.city) {
                  const cityId = cityMap.value.get(form.city);
                  if (cityId) {
                    const districtRes = (await getDistricts(cityId)) as any;
                    if (districtRes.code === 200 && districtRes.data) {
                      districtOptions.value = districtRes.data.map(
                        (item: Region) => ({
                          label: item.name,
                          value: item.name,
                        })
                      );
                    }
                  }
                }
              }
            }
          }
        }
      } catch (error) {
        console.error('加载省市区级联数据失败:', error);
        Message.error('加载省市区级联数据失败');
      }
    }
  }

  // 处理提交
  async function handleSubmit() {
    try {
      // 表单验证
      await formRef.value?.validate();

      // 验证时段设置
      validateTimeRanges();
      if (!timeRangesValid.value) {
        Message.error('请先修正时段设置问题');
        return false;
      }

      // 构建提交数据
      const submitData = {
        ...form,
        carBillingMethod: {
          elecPriceSetting: {
            topTimeAmount:
              form.carBillingMethod?.elecPriceSetting?.topTimeAmount || '0',
            peakTimeAmount:
              form.carBillingMethod?.elecPriceSetting?.peakTimeAmount || '0',
            normalTimeAmount:
              form.carBillingMethod?.elecPriceSetting?.normalTimeAmount || '0',
            valleyTimeAmount:
              form.carBillingMethod?.elecPriceSetting?.valleyTimeAmount || '0',
            topTimeServiceAmount:
              form.carBillingMethod?.elecPriceSetting?.topTimeServiceAmount ||
              '0',
            peakTimeServiceAmount:
              form.carBillingMethod?.elecPriceSetting?.peakTimeServiceAmount ||
              '0',
            normalTimeServiceAmount:
              form.carBillingMethod?.elecPriceSetting
                ?.normalTimeServiceAmount || '0',
            valleyTimeServiceAmount:
              form.carBillingMethod?.elecPriceSetting
                ?.valleyTimeServiceAmount || '0',
          },
          intervalSettingList: timePeriods.value.map((period) => ({
            startTime: period.startTime,
            endTime: period.endTime,
            timeType: period.type,
            amount: getAmountByTimeType(period.type),
            serviceAmount: getServiceAmountByTimeType(period.type),
          })),
        },
        carChargingMethod: {
          isFullStop: form.carChargingMethod?.isFullStop || 0,
          billingType: form.carChargingMethod?.billingType || 1,
          values:
            form.carChargingMethod?.values.map((item) => ({
              billingType: item.billingType,
              billingName: `${getItemValue(item)}元`,
              billingValue: getItemValue(item),
              isSelect: isItemSelected(item) ? 1 : 0,
            })) || [],
        },
      };

      let res: any;
      if (isEdit.value) {
        res = await updateCarChargingGroup(submitData);
      } else {
        res = await addCarChargingGroup(submitData);
      }

      if (res.code === 200) {
        Message.success(isEdit.value ? '更新成功' : '新增成功');
        visible.value = false;
        fetchData();
        return true;
      } else {
        Message.error(
          `${isEdit.value ? '更新' : '新增'}失败: ${res.message || '未知错误'}`
        );
        return false;
      }
    } catch (err) {
      console.error('表单提交异常:', err);
      Message.error(isEdit.value ? '更新失败' : '新增失败');
      return false;
    }
  }

  // 删除
  async function handleDelete(record: CarChargingGroupDetailVo) {
    try {
      if (!record.id) {
        Message.error('站点ID不存在');
        return;
      }

      const res = await deleteCarChargingGroup(record.id);
      if (res.code === 200) {
        Message.success('删除成功');
        // 刷新列表
        fetchData();
      } else {
        Message.error(`删除失败: ${res.message || '未知错误'}`);
      }
    } catch (err) {
      console.error('删除站点异常:', err);
      Message.error('删除失败');
    }
  }

  // 查看设备
  function viewDevices(record: CarChargingGroupDetailVo) {
    router.push({
      path: '/station/device',
      query: {
        groupId: record.id,
        groupName: record.name,
        chargingGroupId: record.id,
      },
    });
  }

  // 获取客户列表
  async function loadPartnerData() {
    partnerLoading.value = true;
    try {
      const res = await getAllPartners({ status: 1 });
      if (res && Array.isArray(res.data)) {
        partnerOptions.value = res.data.map((item: any) => ({
          id: item.id,
          partnerName: item.realName,
        }));
      } else {
        Message.error('获取客户列表失败: 未返回有效数据');
      }
    } catch (error) {
      console.error('获取客户列表异常:', error);
      Message.error('获取客户列表失败');
    } finally {
      partnerLoading.value = false;
    }
  }

  // 加载表单中合伙人选择下拉框数据
  async function loadPartnerSelectData() {
    partnerSelectLoading.value = true;
    try {
      const res = await getAllPartners({ status: 1 });
      if (res && Array.isArray(res.data)) {
        partnerSelectOptions.value = res.data.map((item: any) => ({
          id: item.id,
          partnerName: item.realName,
        }));
      } else {
        Message.error('获取合伙人列表失败: 未返回有效数据');
      }
    } catch (error) {
      console.error('获取合伙人列表异常:', error);
      Message.error('获取合伙人列表失败');
    } finally {
      partnerSelectLoading.value = false;
    }
  }

  // 获取标签列表
  async function loadLabelData() {
    try {
      const res = await getCarChargingGroupLabelList();
      if (res && res.code === 200) {
        labelOptions.value = res.data || [];
      } else {
        Message.error('获取标签列表失败');
      }
    } catch (error) {
      console.error('获取标签列表异常:', error);
      Message.error('获取标签列表失败');
    }
  }

  // 加载省份数据
  async function loadProvinceData() {
    try {
      const res = (await getProvinces()) as any;
      console.log('获取省份列表响应:', res);
      if (res.code === 200 && res.data) {
        provinceOptions.value = res.data.map((item: Region) => ({
          label: item.name,
          value: item.name,
        }));
        // 存储省份ID映射
        res.data.forEach((item: Region) => {
          provinceMap.value.set(item.name, item.id);
        });
        console.log('省份数据加载成功:', provinceOptions.value);
        console.log('省份ID映射:', provinceMap.value);
      } else {
        console.error('获取省份列表失败:', res);
        Message.error('获取省份列表失败: ' + (res.message || '未返回数据'));
      }
    } catch (error) {
      console.error('获取省份列表异常:', error);
      Message.error('获取省份列表失败');
    }
  }

  // 初始化地图
  function initMap() {
    if (!AMap) {
      console.error('高德地图 API 未加载成功');
      Message.error('地图加载失败，请检查网络或刷新页面重试');
      return;
    }

    try {
      // 默认中心点
      const center = [116.397428, 39.90923];

      // 创建地图实例
      map = new AMap.Map('map-container', {
        zoom: 13,
        center,
      });

      // 监听地图错误事件
      map.on('error', (e: any) => {
        console.error('地图加载错误:', e);
        Message.error('地图加载出现错误，请检查控制台');
      });

      // 创建标记
      marker = new AMap.Marker({
        position: center,
        draggable: true,
        cursor: 'move',
      });

      // 将标记添加到地图
      map.add(marker);

      // 初始化地理编码器
      try {
        if (!geocoder) {
          geocoder = new AMap.Geocoder({
            city: '全国', // 城市，默认全国
            radius: 1000, // 范围，默认1000米
          });
        }
      } catch (geocoderError) {
        console.error('地理编码器初始化失败:', geocoderError);
        Message.warning('地理编码器初始化失败，地址搜索功能可能不可用');
      }

      // 监听点击事件
      map.on('click', (e: any) => {
        const lnglat = e.lnglat;
        marker.setPosition(lnglat);
        form.changingGroupLon = lnglat.getLng();
        form.chargingGroupLat = lnglat.getLat();

        // 反向地理编码，获取地址信息
        getAddressByLngLat(lnglat);
      });

      // 监听标记拖拽事件
      marker.on('dragend', (e: any) => {
        const lnglat = marker.getPosition();
        form.changingGroupLon = lnglat.getLng();
        form.chargingGroupLat = lnglat.getLat();

        // 反向地理编码，获取地址信息
        getAddressByLngLat(lnglat);
      });
    } catch (error) {
      console.error('初始化地图失败:', error);
      Message.error('初始化地图失败，请检查网络或刷新页面重试');
    }
  }

  // 根据经纬度获取地址信息
  function getAddressByLngLat(lnglat: any) {
    if (!geocoder) return;

    geocoder.getAddress(lnglat, (status: string, result: any) => {
      if (status === 'complete' && result.info === 'OK') {
        const address = result.regeocode;
        if (address) {
          // 如果用户尚未输入地址信息，则自动填充
          const addressComponent = address.addressComponent;

          // 只有当用户未选择省市区时才自动填充
          if (!form.province && addressComponent.province) {
            form.province = addressComponent.province;
            handleFormProvinceChange(form.province);
          }

          if (!form.city && addressComponent.city) {
            // 处理直辖市的情况
            if (
              addressComponent.city.length === 0 &&
              ['北京市', '上海市', '天津市', '重庆市'].includes(form.province)
            ) {
              form.city = form.province;
            } else {
              form.city = addressComponent.city;
            }
            handleFormCityChange(form.city);
          }

          if (!form.district && addressComponent.district) {
            form.district = addressComponent.district;
          }

          // 如果详细地址为空，则自动填充
          if (!form.address) {
            // 使用街道和门牌号作为详细地址
            const street = addressComponent.township || '';
            const streetNumber = addressComponent.streetNumber || '';
            form.address = (street + streetNumber).trim();

            // 如果街道和门牌号都为空，则使用格式化地址
            if (!form.address && address.formattedAddress) {
              // 移除省市区信息，只保留详细地址
              let detailAddress = address.formattedAddress;
              if (form.province) {
                detailAddress = detailAddress.replace(form.province, '');
              }
              if (form.city) {
                detailAddress = detailAddress.replace(form.city, '');
              }
              if (form.district) {
                detailAddress = detailAddress.replace(form.district, '');
              }
              form.address = detailAddress.trim();
            }
          }
        }
      }
    });
  }

  // 根据地址搜索位置
  function searchAddress() {
    if (!AMap) {
      Message.error('地图未加载成功，无法使用地址搜索功能');
      return;
    }

    if (!form.address) {
      Message.warning('请先输入详细地址');
      return;
    }

    // 构建完整地址
    let fullAddress = '';
    if (form.province) {
      fullAddress += form.province;
    }
    if (form.city) {
      fullAddress += form.city;
    }
    if (form.district) {
      fullAddress += form.district;
    }
    fullAddress += form.address;

    console.log('搜索地址:', fullAddress);

    // 显示加载提示
    Message.loading('正在搜索地址...');

    // 构建搜索 URL
    const searchUrl = `https://restapi.amap.com/v3/geocode/geo?key=23c24009c5a2548156cea739bef3ab7c&address=${encodeURIComponent(
      fullAddress
    )}&city=${encodeURIComponent(form.city || '')}`;

    // 使用 fetch 发送请求
    fetch(searchUrl)
      .then((response) => response.json())
      .then((result) => {
        // 清除加载提示
        Message.clear();

        console.log('地址搜索结果:', result);

        if (
          result.status === '1' &&
          result.geocodes &&
          result.geocodes.length > 0
        ) {
          const location = result.geocodes[0].location.split(',');
          const lng = parseFloat(location[0]);
          const lat = parseFloat(location[1]);

          form.changingGroupLon = lng;
          form.chargingGroupLat = lat;

          // 更新地图位置
          marker.setPosition([lng, lat]);
          map.setCenter([lng, lat]);
          map.setZoom(15);

          Message.success('地址定位成功');
        } else {
          Message.warning('未找到匹配的地址位置');
          // 尝试使用备选方案
          tryAlternativeSearch(fullAddress);
        }
      })
      .catch((error) => {
        console.error('地址搜索失败:', error);
        Message.error('地址搜索失败，请稍后重试');
        // 尝试使用备选方案
        tryAlternativeSearch(fullAddress);
      });
  }

  // 备选方案：使用高德地图 Web 服务 API 搜索地址
  function tryAlternativeSearch(address: string) {
    console.log('尝试使用备选方案搜索地址:', address);

    // 构建搜索 URL
    const searchUrl = `https://restapi.amap.com/v3/geocode/geo?key=23c24009c5a2548156cea739bef3ab7c&address=${encodeURIComponent(
      address
    )}&city=${encodeURIComponent(form.city || '')}`;

    // 使用 JSONP 方式请求，避免跨域问题
    const script = document.createElement('script');
    const callbackName =
      'amap_geocode_callback_' + Math.random().toString(36).substr(2, 9);

    // 创建全局回调函数
    (window as any)[callbackName] = function (result: any) {
      try {
        console.log('备选方案搜索结果:', result);

        if (
          result.status === '1' &&
          result.geocodes &&
          result.geocodes.length > 0
        ) {
          const location = result.geocodes[0].location.split(',');
          const lng = parseFloat(location[0]);
          const lat = parseFloat(location[1]);

          form.changingGroupLon = lng;
          form.chargingGroupLat = lat;

          // 更新地图位置
          if (marker && map) {
            marker.setPosition([lng, lat]);
            map.setCenter([lng, lat]);
            map.setZoom(15);

            Message.success('地址定位成功（备选方案）');
          } else {
            Message.success('地址定位成功，但地图未加载，已保存经纬度');
          }
        } else {
          console.error('备选方案搜索失败:', result);
          Message.error('备选方案搜索失败: ' + (result.info || '未知错误'));
        }
      } catch (error) {
        console.error('备选方案搜索异常:', error);
      } finally {
        // 清理：移除脚本和回调函数
        document.body.removeChild(script);
        delete (window as any)[callbackName];
      }
    };

    // 设置脚本 URL，添加回调参数
    script.src = searchUrl + '&callback=' + callbackName;
    script.async = true;

    // 处理加载错误
    script.onerror = function (error) {
      console.error('备选方案搜索加载失败:', error);
      Message.error('备选方案搜索加载失败，请检查网络连接');
      document.body.removeChild(script);
      delete (window as any)[callbackName];

      // 最后的备选方案：使用本地坐标拾取器
      Message.info(
        '您可以使用手动输入经纬度的方式，通过高德坐标拾取器获取坐标'
      );
    };

    // 添加脚本到文档
    document.body.appendChild(script);
  }

  // 打开坐标拾取器
  function openCoordinatePicker() {
    // 打开高德地图坐标拾取器
    const url = 'https://lbs.amap.com/tools/picker';
    window.open(url, '_blank');

    Message.info('请在坐标拾取器中选择位置，然后复制经纬度到表单中');
  }

  // 手动输入坐标
  function inputCoordinates() {
    const coordsInput = window.prompt(
      '请输入经纬度（格式：经度,纬度）',
      form.changingGroupLon && form.chargingGroupLat
        ? `${form.changingGroupLon},${form.chargingGroupLat}`
        : ''
    );
    if (coordsInput) {
      const coords = coordsInput.split(',');
      if (coords.length === 2) {
        const lng = parseFloat(coords[0].trim());
        const lat = parseFloat(coords[1].trim());

        if (!isNaN(lng) && !isNaN(lat)) {
          form.changingGroupLon = lng;
          form.chargingGroupLat = lat;

          // 更新地图位置
          if (marker && map) {
            marker.setPosition([lng, lat]);
            map.setCenter([lng, lat]);
            map.setZoom(15);
            Message.success('已更新地图位置');
          } else {
            Message.success('已保存经纬度，但地图未加载');
          }
        } else {
          Message.error('无效的经纬度格式');
        }
      } else {
        Message.error('无效的经纬度格式，请使用"经度,纬度"格式');
      }
    }
  }

  // 处理省份变化
  async function handleFormProvinceChange(value: string) {
    console.log('表单省份变化:', value);
    form.city = '';
    form.district = '';
    if (value) {
      try {
        const provinceId = provinceMap.value.get(value);
        console.log('获取到省份ID:', provinceId, '省份名称:', value);
        console.log('当前省份映射表:', provinceMap.value);
        if (provinceId) {
          const res = (await getCities(provinceId)) as any;
          console.log('获取城市列表响应:', res);
          if (res.code === 200 && res.data) {
            formCityOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            // 更新城市ID映射
            res.data.forEach((item: Region) => {
              cityMap.value.set(item.name, item.id);
            });
            console.log('表单城市列表加载成功:', formCityOptions.value);
          } else {
            console.error('获取城市列表失败:', res);
            Message.error('获取城市列表失败: ' + (res.message || '未返回数据'));
          }
        } else {
          console.error('未找到省份对应的ID:', value);
          console.log('所有省份选项:', provinceOptions.value);
          Message.error('未找到省份对应的ID');
        }
      } catch (error) {
        console.error('获取城市列表异常:', error);
        Message.error('获取城市列表失败');
        formCityOptions.value = [];
      }
    } else {
      formCityOptions.value = [];
    }
    districtOptions.value = [];
  }

  // 处理城市变化
  async function handleFormCityChange(value: string) {
    console.log('表单城市变化:', value);
    form.district = '';
    if (form.province && value) {
      try {
        const cityId = cityMap.value.get(value);
        console.log('获取到城市ID:', cityId, '城市名称:', value);
        console.log('当前城市映射表:', cityMap.value);
        if (cityId) {
          const res = (await getDistricts(cityId)) as any;
          console.log('获取区县列表响应:', res);
          if (res.code === 200 && res.data) {
            districtOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            console.log('区县列表加载成功:', districtOptions.value);
          } else {
            console.error('获取区县列表失败:', res);
            Message.error('获取区县列表失败: ' + (res.message || '未返回数据'));
          }
        } else {
          console.error('未找到城市对应的ID:', value);
          console.log('所有城市选项:', formCityOptions.value);
          Message.error('未找到城市对应的ID');
        }
      } catch (error) {
        console.error('获取区县列表异常:', error);
        Message.error('获取区县列表失败');
        districtOptions.value = [];
      }
    } else {
      districtOptions.value = [];
    }
  }

  // 防抖处理的地址搜索
  const debounceSearchAddress = debounce((value: string) => {
    if (value && form.province && form.city) {
      // 构建完整地址
      let fullAddress = '';
      if (form.province) {
        fullAddress += form.province;
      }
      if (form.city) {
        fullAddress += form.city;
      }
      if (form.district) {
        fullAddress += form.district;
      }
      fullAddress += value;

      // 构建搜索 URL
      const searchUrl = `https://restapi.amap.com/v3/geocode/geo?key=23c24009c5a2548156cea739bef3ab7c&address=${encodeURIComponent(
        fullAddress
      )}&city=${encodeURIComponent(form.city || '')}`;

      // 使用 fetch 发送请求
      fetch(searchUrl)
        .then((response) => response.json())
        .then((result) => {
          console.log('地址搜索结果:', result);

          if (
            result.status === '1' &&
            result.geocodes &&
            result.geocodes.length > 0
          ) {
            const location = result.geocodes[0].location.split(',');
            const lng = parseFloat(location[0]);
            const lat = parseFloat(location[1]);

            form.changingGroupLon = lng;
            form.chargingGroupLat = lat;

            // 更新地图位置
            if (marker && map) {
              marker.setPosition([lng, lat]);
              map.setCenter([lng, lat]);
              map.setZoom(15);
            }
          }
        })
        .catch((error) => {
          console.error('地址搜索失败:', error);
        });
    }
  }, 1000);

  // 初始化24小时分段
  function initTimePeriods() {
    // 初始化为一个覆盖整天的时段
    timePeriods.value = [
      {
        startTime: '00:00',
        endTime: '24:00',
        type: 2, // 平时段（默认）
      },
    ];

    // 验证时段
    validateTimeRanges();

    // 更新表单字段
    updateTimePeriodSettings();

    //确保费用设置为0
    if (form.carBillingMethod && form.carBillingMethod.elecPriceSetting) {
      form.carBillingMethod.elecPriceSetting = {
        topTimeAmount: '0',
        peakTimeAmount: '0',
        normalTimeAmount: '0',
        valleyTimeAmount: '0',
        serviceAmount: '0',
        topTimeServiceAmount: '0',
        peakTimeServiceAmount: '0',
        normalTimeServiceAmount: '0',
        valleyTimeServiceAmount: '0',
      };
    }
  }

  // 验证时段设置是否有效
  function validateTimeRanges() {
    // 如果没有时段，则无效
    if (timePeriods.value.length === 0) {
      timeRangesValid.value = false;
      timeRangeErrorMessage.value = '请添加至少一个时段';
      return;
    }

    // 将所有时段转换为分钟数进行排序和验证
    const ranges: { start: number; end: number; type: number }[] = [];

    for (const period of timePeriods.value) {
      // 格式化时间为 "HH:mm"
      const startTimeParts = period.startTime.split(':');
      const endTimeParts = period.endTime.split(':');

      if (startTimeParts.length !== 2 || endTimeParts.length !== 2) {
        timeRangesValid.value = false;
        timeRangeErrorMessage.value = '时间格式错误，请使用 HH:mm 格式';
        return;
      }

      const startHour = parseInt(startTimeParts[0]);
      const startMinute = parseInt(startTimeParts[1]);
      const endHour = parseInt(endTimeParts[0]);
      const endMinute = parseInt(endTimeParts[1]);

      // 验证时间是否为整点或半点
      if (
        startHour < 0 ||
        startHour > 23 ||
        endHour < 0 ||
        endHour > 24 ||
        (startMinute !== 0 && startMinute !== 30) ||
        (endMinute !== 0 && endMinute !== 30)
      ) {
        timeRangesValid.value = false;
        timeRangeErrorMessage.value = '时间必须为整点或半点（如08:00, 08:30）';
        return;
      }

      // 特殊处理24:00这个结束时间
      const startMinutes = startHour * 60 + startMinute;
      let endMinutes = endHour * 60 + endMinute;
      if (endHour === 24) endMinutes = 24 * 60;

      // 开始时间必须早于结束时间
      if (startMinutes >= endMinutes) {
        timeRangesValid.value = false;
        timeRangeErrorMessage.value = '时段的开始时间必须早于结束时间';
        return;
      }
      ranges.push({
        start: startMinutes,
        end: endMinutes,
        type: period.type,
      });
    }

    // 按开始时间排序
    ranges.sort((a, b) => a.start - b.start);

    // 检查时段是否连续覆盖24小时
    if (ranges[0].start !== 0) {
      timeRangesValid.value = false;
      timeRangeErrorMessage.value = '第一个时段必须从00:00开始';
      return;
    }

    // 检查最后一个时段是否结束于24:00
    if (ranges[ranges.length - 1].end !== 24 * 60) {
      timeRangesValid.value = false;
      timeRangeErrorMessage.value = '最后一个时段必须结束于24:00';
      return;
    }

    // 检查时段之间是否连续无重叠
    for (let i = 0; i < ranges.length - 1; i++) {
      if (ranges[i].end !== ranges[i + 1].start) {
        timeRangesValid.value = false;
        timeRangeErrorMessage.value =
          '时段之间必须连续无缝衔接，不能有重叠或空隙';
        return;
      }
    }

    // 所有验证通过
    timeRangesValid.value = true;
    timeRangeErrorMessage.value = '';

    // 按照排序后的顺序重新整理时段
    const sortedPeriods: TimePeriod[] = [];
    for (const range of ranges) {
      const startHour = Math.floor(range.start / 60);
      const startMinute = range.start % 60;
      const endHour = Math.floor(range.end / 60);
      const endMinute = range.end % 60;

      sortedPeriods.push({
        startTime: `${startHour.toString().padStart(2, '0')}:${startMinute
          .toString()
          .padStart(2, '0')}`,
        endTime: `${endHour.toString().padStart(2, '0')}:${endMinute
          .toString()
          .padStart(2, '0')}`,
        type: range.type,
      });
    }

    // 更新时段列表
    timePeriods.value = sortedPeriods;

    // 更新表单
    updateTimePeriodSettings();
  }

  // 添加新时段
  function addTimePeriod() {
    // 如果当前没有时段
    if (timePeriods.value.length === 0) {
      timePeriods.value.push({
        startTime: '00:00',
        endTime: '24:00',
        type: 2, // 默认为平时段
      });

      validateTimeRanges();
      return;
    }

    // 尝试找到一个可以分割的时段（时长至少1小时）
    let splitIndex = -1;
    let splitTime = '';

    for (let i = 0; i < timePeriods.value.length; i++) {
      const period = timePeriods.value[i];
      const startParts = period.startTime.split(':');
      const endParts = period.endTime.split(':');

      const startHour = parseInt(startParts[0]);
      const startMinute = parseInt(startParts[1]);
      const endHour = parseInt(endParts[0]);
      const endMinute = parseInt(endParts[1]);

      // 特殊处理24:00
      let startMinutes = startHour * 60 + startMinute;
      let endMinutes = endHour * 60 + endMinute;
      if (endHour === 24) endMinutes = 24 * 60;

      // 如果时段长度至少1小时（60分钟）
      if (endMinutes - startMinutes >= 60) {
        // 计算中点（保证是整点或半点）
        const totalMinutes = endMinutes - startMinutes;
        const halfwayMinutes = Math.floor(totalMinutes / 2);
        const midpointMinutes = startMinutes + halfwayMinutes;

        // 向下取整到最近的半小时
        const roundedMinutes = Math.floor(midpointMinutes / 30) * 30;

        // 确保不与开始时间相同
        if (roundedMinutes > startMinutes) {
          const midHour = Math.floor(roundedMinutes / 60);
          const midMinute = roundedMinutes % 60;

          splitIndex = i;
          splitTime = `${midHour.toString().padStart(2, '0')}:${midMinute
            .toString()
            .padStart(2, '0')}`;
          break;
        }
      }
    }

    // 如果找到可分割的时段
    if (splitIndex >= 0 && splitTime) {
      const originalPeriod = timePeriods.value[splitIndex];

      // 创建新时段
      const newPeriod = {
        startTime: splitTime,
        endTime: originalPeriod.endTime,
        type: originalPeriod.type,
      };

      // 修改原时段的结束时间
      originalPeriod.endTime = splitTime;

      // 在原时段后插入新时段
      timePeriods.value.splice(splitIndex + 1, 0, newPeriod);

      // 验证并更新
      validateTimeRanges();
    } else {
      Message.warning('无法添加更多时段，现有时段无法分割');
    }
  }

  // 删除时段
  function removeTimePeriod(index: number) {
    // 如果只剩一个时段，不允许删除
    if (timePeriods.value.length <= 1) {
      Message.warning('至少需要保留一个时段');
      return;
    }

    // 获取要删除的时段
    const periodToRemove = timePeriods.value[index];

    // 如果不是第一个或最后一个时段，需要合并前后时段
    if (index > 0 && index < timePeriods.value.length - 1) {
      // 获取前一个时段
      const prevPeriod = timePeriods.value[index - 1];

      // 更新前一个时段的结束时间为当前时段的结束时间
      prevPeriod.endTime = periodToRemove.endTime;

      // 删除当前时段
      timePeriods.value.splice(index, 1);
    } else if (index === 0) {
      // 如果是第一个时段，把下一个时段的开始时间改为00:00
      const nextPeriod = timePeriods.value[1];
      nextPeriod.startTime = '00:00';

      // 删除当前时段
      timePeriods.value.splice(index, 1);
    } else {
      // 如果是最后一个时段，把前一个时段的结束时间改为24:00
      const prevPeriod = timePeriods.value[index - 1];
      prevPeriod.endTime = '24:00';

      // 删除当前时段
      timePeriods.value.splice(index, 1);
    }

    // 验证并更新
    validateTimeRanges();

    Message.success('已删除时段');
  }

  // 更新时段设置
  function updateTimePeriodSettings() {
    console.log('更新时段设置，当前时段数据:', timePeriods.value);

    // 只有时段设置有效时才更新表单
    if (timeRangesValid.value) {
      // 确保carBillingMethod对象存在
      if (!form.carBillingMethod) {
        form.carBillingMethod = {
          elecPriceSetting: {
            topTimeAmount: '0',
            peakTimeAmount: '0',
            normalTimeAmount: '0',
            valleyTimeAmount: '0',
            serviceAmount: '0',
            topTimeServiceAmount: '0',
            peakTimeServiceAmount: '0',
            normalTimeServiceAmount: '0',
            valleyTimeServiceAmount: '0',
          },
          intervalSettingList: [],
        };
      }

      // 更新intervalSettingList
      form.carBillingMethod.intervalSettingList = timePeriods.value.map(
        (period) => {
          // 获取该时段类型对应的电费和服务费
          const amount = getAmountByTimeType(period.type);
          const serviceAmount = getServiceAmountByTimeType(period.type);

          return {
            startTime: period.startTime,
            endTime: period.endTime,
            timeType: period.type,
            amount: amount,
            serviceAmount: serviceAmount,
            isCurrent: 1,
            totalMoney: (
              parseFloat(amount) + parseFloat(serviceAmount)
            ).toString(),
          };
        }
      );

      // 保存时段设置到表单
      form.timePeriodSettings = JSON.stringify(timePeriods.value);

      console.log('更新后的计费设置:', form.carBillingMethod);
    } else {
      console.warn('时段设置无效，未更新表单');
    }
  }

  // 添加金额选择项
  function addBillingConfig() {
    if (!form.carChargingMethod) {
      form.carChargingMethod = {
        isFullStop: 0,
        values: [],
      };
    }

    // 获取当前最大金额，用于建议新的金额值
    let maxValue = 0;
    form.carChargingMethod.values.forEach((item) => {
      const value = parseFloat(getItemValue(item));
      if (!isNaN(value) && value > maxValue) {
        maxValue = value;
      }
    });

    // 新金额建议值为当前最大值加10
    const suggestedValue = maxValue + 10;

    // 使用新的数据结构添加金额
    form.carChargingMethod.values.push({
      value: suggestedValue.toString(),
      billingType: 1,
      selected: false,
    });
  }

  // 删除金额选择项
  function removeBillingConfig(index: number) {
    form.carChargingMethod.values.splice(index, 1);
  }

  // 根据时段类型获取对应电费
  function getAmountByTimeType(type: number): string {
    const elecPriceSetting = form.carBillingMethod?.elecPriceSetting;
    if (!elecPriceSetting) return '0';

    switch (type) {
      case 0:
        return elecPriceSetting.topTimeAmount || '0';
      case 1:
        return elecPriceSetting.peakTimeAmount || '0';
      case 2:
        return elecPriceSetting.normalTimeAmount || '0';
      case 3:
        return elecPriceSetting.valleyTimeAmount || '0';
      default:
        return '0';
    }
  }

  // 根据时段类型获取对应服务费
  function getServiceAmountByTimeType(type: number): string {
    const elecPriceSetting = form.carBillingMethod?.elecPriceSetting;
    if (!elecPriceSetting) return '0';

    switch (type) {
      case 0:
        return elecPriceSetting.topTimeServiceAmount || '0';
      case 1:
        return elecPriceSetting.peakTimeServiceAmount || '0';
      case 2:
        return elecPriceSetting.normalTimeServiceAmount || '0';
      case 3:
        return elecPriceSetting.valleyTimeServiceAmount || '0';
      default:
        return '0';
    }
  }

  // 获取金额项的值(兼容新旧数据结构)
  function getItemValue(item: any) {
    if (item.value !== undefined) {
      return item.value;
    }
    if (item.billingValue !== undefined) {
      return item.billingValue;
    }
    return '0';
  }

  function getItemValueUnit(item: any) {
    console.log('item:', item);
    let itemValue = '';
    if (item.value !== undefined) {
      itemValue = item.value;
    }
    if (item.billingValue !== undefined) {
      itemValue = item.billingValue;
    }
    return item.billingType === 2 ? itemValue : `${itemValue}'元'`;
  }

  // 判断金额项是否被选中(兼容新旧数据结构)
  function isItemSelected(item) {
    if (item.selected !== undefined) {
      return !!item.selected;
    }
    if (item.isSelect !== undefined) {
      return item.isSelect === 1;
    }
    return false;
  }

  // 切换金额项选中状态(兼容新旧数据结构)
  function toggleBillingSelection(index) {
    const item = form.carChargingMethod.values[index];

    // 兼容新旧数据结构
    if ('selected' in item) {
      item.selected = !item.selected;
    } else if ('isSelect' in item) {
      item.isSelect = item.isSelect === 1 ? 0 : 1;
    } else {
      // 如果两种属性都不存在，添加selected属性
      item.selected = true;
    }
  }

  // 切换金额选择
  function toggleBillingValue(index: number) {
    toggleBillingSelection(index);
  }

  // 添加自定义金额
  function addCustomValue() {
    if (!customValue.value) {
      Message.warning('请输入自定义金额');
      return;
    }

    // 检查是否已存在相同金额
    const existingValue = form.carChargingMethod.values.find((item) => {
      const itemValue = getItemValue(item);
      return parseFloat(itemValue) === customValue.value;
    });

    if (existingValue) {
      Message.warning('该金额已存在');
      return;
    }

    // 使用新的数据结构添加自定义金额
    form.carChargingMethod.values.push({
      value: customValue.value.toString(),
      billingType: 1,
      selected: false,
    });

    customValue.value = undefined;
  }

  onMounted(() => {
    fetchData();
    loadPartnerData();
    loadPartnerSelectData();
    loadLabelData();
    loadProvinceData();

    // 初始化24小时分段设置
    initTimePeriods();

    // 设置安全密钥配置（必须在加载地图脚本之前设置）
    window._AMapSecurityConfig = {
      securityJsCode: AMAP_CONFIG.securityJsCode,
      serviceHost: `https://restapi.amap.com`,
    };

    // 加载高德地图
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=${AMAP_CONFIG.version}&key=${
      AMAP_CONFIG.key
    }&plugin=${AMAP_CONFIG.plugins.join(',')}`;

    script.onerror = (error) => {
      console.error('高德地图 API 加载失败:', error);
      Message.error('高德地图加载失败，将使用手动输入经纬度的方式');
    };

    script.onload = () => {
      if (window.AMap) {
        AMap = window.AMap;
        console.log('高德地图 API 加载成功');
        // 地图加载成功后初始化地图
        setTimeout(() => {
          initMap();
        }, 100);
      } else {
        console.error('高德地图 API 加载失败: AMap 对象不存在');
      }
    };

    document.head.appendChild(script);
  });

  onBeforeUnmount(() => {
    // 销毁地图实例
    if (map) {
      map.destroy();
      map = null;
    }
  });

  const customValue = ref<number>();

  // 处理充电金额项回显
  function processBillingValues() {
    console.log('处理充电金额项回显，当前数据:', form.carChargingMethod);

    // 确保充电方式数据存在
    if (!form.carChargingMethod) {
      form.carChargingMethod = {
        isFullStop: 0,
        values: [
          ...formInitialState.carChargingMethod.values.map((item) => ({
            value: item.billingValue,
            selected: item.isSelect === 1,
          })),
        ],
      };
      console.log('充电方式对象不存在，已初始化为默认值');
      return;
    }

    // 处理API返回值可能的情况
    if (typeof form.carChargingMethod === 'string') {
      try {
        form.carChargingMethod = JSON.parse(form.carChargingMethod);
        console.log(
          '解析字符串格式的carChargingMethod:',
          form.carChargingMethod
        );
      } catch (e) {
        console.error('解析carChargingMethod字符串失败:', e);
        form.carChargingMethod = {
          isFullStop: 0,
          values: [
            ...formInitialState.carChargingMethod.values.map((item) => ({
              value: item.billingValue,
              billingType: item.billingType,
              selected: item.isSelect === 1,
            })),
          ],
        };
        console.log('解析充电方式字符串失败，已初始化为默认值');
        return;
      }
    }

    // 确保values数组存在且不为空
    if (
      !Array.isArray(form.carChargingMethod.values) ||
      form.carChargingMethod.values.length === 0
    ) {
      console.log('充电金额数组为空，使用默认值');
      // 使用初始化的默认values，但是需要转换为新格式
      form.carChargingMethod.values =
        formInitialState.carChargingMethod.values.map((item) => ({
          value: item.billingValue,
          billingType: item.billingType,
          selected: item.isSelect === 1,
        }));
      return;
    }

    // 检查API返回的格式类型
    const firstItem = form.carChargingMethod.values[0];

    // 处理API可能返回的不同结构
    if (firstItem) {
      // 检查是否是旧格式（具有billingName, billingValue, isSelect字段）
      if (
        typeof firstItem === 'object' &&
        ('billingName' in firstItem ||
          'billingValue' in firstItem ||
          'isSelect' in firstItem)
      ) {
        console.log('检测到旧格式的充电金额数据');
        // 转换为新格式
        form.carChargingMethod.values = form.carChargingMethod.values.map(
          (item) => ({
            value: item.billingValue ? String(item.billingValue) : '0',
            billingType: item.billingType,
            selected: item.isSelect === 1,
          })
        );
      }
      // 检查是否是预期格式（具有value和selected字段）
      else if (
        typeof firstItem === 'object' &&
        ('value' in firstItem || 'selected' in firstItem)
      ) {
        console.log('检测到预期格式的充电金额数据');
        // 确保所有数据格式正确
        form.carChargingMethod.values = form.carChargingMethod.values.map(
          (item) => ({
            value: String(item.value || '0'),
            billingType: item.billingType,
            selected: !!item.selected,
          })
        );
      }
      // 处理其他可能的格式（如纯值数组）
      else {
        console.log('检测到其他格式的充电金额数据，尝试转换');
        // 尝试将值转换为正确格式
        form.carChargingMethod.values = form.carChargingMethod.values.map(
          (item, index) => {
            if (typeof item === 'string' || typeof item === 'number') {
              return {
                value: String(item),
                billingType: 1, // 默认计费类型
                selected: index === 0, // 默认选中第一个
              };
            }
            // 对于无法解析的格式，返回默认值
            return {
              value: '10',
              selected: index === 0,
            };
          }
        );
      }
    }

    // 确保至少有一个选项被选中
    const hasSelectedItem = form.carChargingMethod.values.some(
      (item) => item.selected
    );
    if (!hasSelectedItem && form.carChargingMethod.values.length > 0) {
      form.carChargingMethod.values[0].selected = true;
    }

    // 确保isFullStop和billingType字段是数字类型
    if (form.carChargingMethod.isFullStop !== undefined) {
      form.carChargingMethod.isFullStop = Number(
        form.carChargingMethod.isFullStop
      );
    } else {
      form.carChargingMethod.isFullStop = 0;
    }

    if (form.carChargingMethod.billingType !== undefined) {
      form.carChargingMethod.billingType = Number(
        form.carChargingMethod.billingType
      );
    } else {
      form.carChargingMethod.billingType = 1;
    }

    console.log('处理后的充电金额数据:', form.carChargingMethod);
  }

  // 处理计费设置回显
  function processBillingSettings() {
    console.log('处理计费设置回显，当前数据:', form.carBillingMethod);

    // 确保carBillingMethod对象存在
    if (!form.carBillingMethod) {
      form.carBillingMethod = {
        elecPriceSetting: {
          topTimeAmount: 0,
          peakTimeAmount: 0,
          normalTimeAmount: 0,
          valleyTimeAmount: 0,
          serviceAmount: 0,
          topTimeServiceAmount: 0,
          peakTimeServiceAmount: 0,
          normalTimeServiceAmount: 0,
          valleyTimeServiceAmount: 0,
        },
        intervalSettingList: [],
      };
      console.log('初始化默认计费设置');
      return;
    }

    // 如果carBillingMethod是字符串，尝试解析
    if (typeof form.carBillingMethod === 'string') {
      try {
        form.carBillingMethod = JSON.parse(form.carBillingMethod);
        console.log('解析字符串格式的计费设置:', form.carBillingMethod);
      } catch (e) {
        console.error('解析计费设置字符串失败:', e);
        form.carBillingMethod = {
          elecPriceSetting: {
            topTimeAmount: 0,
            peakTimeAmount: 0,
            normalTimeAmount: 0,
            valleyTimeAmount: 0,
            serviceAmount: 0,
            topTimeServiceAmount: 0,
            peakTimeServiceAmount: 0,
            normalTimeServiceAmount: 0,
            valleyTimeServiceAmount: 0,
          },
          intervalSettingList: [],
        };
        return;
      }
    }

    // 确保elecPriceSetting对象存在
    if (!form.carBillingMethod.elecPriceSetting) {
      form.carBillingMethod.elecPriceSetting = {
        topTimeAmount: 0,
        peakTimeAmount: 0,
        normalTimeAmount: 0,
        valleyTimeAmount: 0,
        serviceAmount: 0,
        topTimeServiceAmount: 0,
        peakTimeServiceAmount: 0,
        normalTimeServiceAmount: 0,
        valleyTimeServiceAmount: 0,
      };
      console.log('初始化默认电费设置');
    }

    // 处理elecPriceSetting中的数值，确保所有值都是数字类型
    const elecPriceSetting = form.carBillingMethod.elecPriceSetting;
    const processedSettings = {
      topTimeAmount: convertToNumberOrDefault(elecPriceSetting.topTimeAmount),
      peakTimeAmount: convertToNumberOrDefault(elecPriceSetting.peakTimeAmount),
      normalTimeAmount: convertToNumberOrDefault(
        elecPriceSetting.normalTimeAmount
      ),
      valleyTimeAmount: convertToNumberOrDefault(
        elecPriceSetting.valleyTimeAmount
      ),
      serviceAmount: convertToNumberOrDefault(elecPriceSetting.serviceAmount),
      topTimeServiceAmount: convertToNumberOrDefault(
        elecPriceSetting.topTimeServiceAmount
      ),
      peakTimeServiceAmount: convertToNumberOrDefault(
        elecPriceSetting.peakTimeServiceAmount
      ),
      normalTimeServiceAmount: convertToNumberOrDefault(
        elecPriceSetting.normalTimeServiceAmount
      ),
      valleyTimeServiceAmount: convertToNumberOrDefault(
        elecPriceSetting.valleyTimeServiceAmount
      ),
    };

    // 更新处理后的设置
    form.carBillingMethod.elecPriceSetting = processedSettings;
    console.log('处理后的电费设置:', form.carBillingMethod.elecPriceSetting);

    // 处理intervalSettingList
    if (!Array.isArray(form.carBillingMethod.intervalSettingList)) {
      form.carBillingMethod.intervalSettingList = [];
    }

    // 根据intervalSettingList更新时段设置
    if (form.carBillingMethod.intervalSettingList.length > 0) {
      timePeriods.value = form.carBillingMethod.intervalSettingList.map(
        (interval) => ({
          startTime: interval.startTime,
          endTime: interval.endTime,
          type: Number(interval.timeType), // 确保类型是数字
        })
      );

      // 验证并更新时段设置
      validateTimeRanges();
      updateTimePeriodSettings();
    } else {
      // 如果没有时段设置，初始化默认时段
      initTimePeriods();
    }

    console.log('处理后的计费设置:', form.carBillingMethod);
  }

  // 转换为数字或使用默认值
  function convertToNumberOrDefault(
    value: any,
    defaultValue: number = 0
  ): number {
    if (value === undefined || value === null || value === '') {
      return defaultValue;
    }

    const num = Number(value);
    return isNaN(num) ? defaultValue : num;
  }

  // 重置表单数据
  function resetForm() {
    // 重置表单为初始状态
    Object.assign(form, formInitialState);

    // 重置文件列表
    fileList.value = [];

    // 重置时段设置
    timePeriods.value = [
      {
        startTime: '00:00',
        endTime: '24:00',
        type: 2, // 默认为平时段
      },
    ];

    // 重置自定义金额输入
    customValue.value = undefined;

    // 确保计费方式对象被正确初始化
    form.carBillingMethod = {
      elecPriceSetting: {
        topTimeAmount: '0',
        peakTimeAmount: '0',
        normalTimeAmount: '0',
        valleyTimeAmount: '0',
        serviceAmount: '0',
        topTimeServiceAmount: '0',
        peakTimeServiceAmount: '0',
        normalTimeServiceAmount: '0',
        valleyTimeServiceAmount: '0',
      },
      intervalSettingList: [],
    };

    // 确保充电方式对象被正确初始化
    form.carChargingMethod = {
      isFullStop: 0,
      values: [
        ...formInitialState.carChargingMethod.values.map((item) => ({
          value: item.billingValue,
          billingType: item.billingType,
          selected: item.isSelect === 1,
        })),
      ],
    };

    // 重置表单验证状态
    formRef.value?.clearValidate();
  }

  // 处理金额变化
  function handleAmountChange(field: string, value: number) {
    if (form.carBillingMethod && form.carBillingMethod.elecPriceSetting) {
      form.carBillingMethod.elecPriceSetting[field] = value;
      console.log(`${field} 更新为:`, value);

      // 更新时段设置
      updateTimePeriodSettings();
    }
  }

  // 导出二维码
  async function exportQrCodes(record: CarChargingGroupDetailVo) {
    try {
      Message.loading('正在获取二维码数据...');
      const res = await getChargingGroupQrCodes(record.id);

      if (res.code === 200 && Array.isArray(res.data)) {
        // 创建一个临时的ZIP文件
        const zip = new JSZip();

        // 遍历每个充电桩的二维码
        for (const item of res.data) {
          // 为每个充电桩创建一个文件夹
          const folder = zip.folder(item.chargingCode || '设备');
          if (folder) {
            // 将二维码图片添加到对应的文件夹中
            for (const qrCode of item.qrCodes) {
              try {
                // 生成带设备编号的二维码图片
                const qrCodeDataURL = await generateQRCodeWithLabel(
                  qrCode.qrCode,
                  `设备编号: ${qrCode.chargingCode}`
                );

                // 将base64图片数据转换为二进制
                const base64Data = qrCodeDataURL.split(',')[1];
                if (!base64Data) {
                  console.warn(`二维码数据格式错误: ${qrCode.chargingName}`);
                  continue;
                }
                const imageData = atob(base64Data);
                const arrayBuffer = new ArrayBuffer(imageData.length);
                const uint8Array = new Uint8Array(arrayBuffer);
                for (let i = 0; i < imageData.length; i++) {
                  uint8Array[i] = imageData.charCodeAt(i);
                }

                // 添加信息文本文件，显示编号和URL
                folder.file(
                  `${qrCode.chargingName}_${qrCode.chargingCode}_info.txt`,
                  `充电桩名称: ${qrCode.chargingName}\n` +
                    `充电桩编号: ${qrCode.chargingCode}\n` +
                    `二维码链接: ${qrCode.qrCode}`
                );

                // 添加二维码图片
                folder.file(`${qrCode.chargingCode}.png`, uint8Array);
              } catch (error) {
                console.error(`生成二维码失败: ${qrCode.chargingName}`, error);
              }
            }
          }
        }

        // 生成ZIP文件并下载
        const zipBlob = await zip.generateAsync({ type: 'blob' });
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(zipBlob);
        downloadLink.download = `${record.name || '站点'}_二维码.zip`;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        URL.revokeObjectURL(downloadLink.href);

        Message.success('二维码导出成功');
      } else {
        throw new Error(res.message || '获取二维码失败');
      }
    } catch (error) {
      console.error('导出二维码失败:', error);
      Message.error('导出二维码失败');
    } finally {
      Message.clear();
    }
  }

  // 生成带设备编号的二维码图片
  const generateQRCodeWithLabel = async (
    url: string,
    label: string
  ): Promise<string> => {
    // 先生成二维码图片
    const qrCodeDataURL = await QRCode.toDataURL(url, {
      errorCorrectionLevel: 'H',
      margin: 1,
      width: 300,
      color: {
        dark: '#000000',
        light: '#ffffff',
      },
    });

    // 创建一个临时canvas
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      throw new Error('无法获取canvas上下文');
    }

    // 设置canvas尺寸
    canvas.width = 300;
    canvas.height = 340; // 为标签留出空间

    // 创建图像对象
    const img = new Image();

    // 等待图像加载
    await new Promise<void>((resolve, reject) => {
      img.onload = () => resolve();
      img.onerror = reject;
      img.src = qrCodeDataURL;
    });

    // 绘制二维码图像
    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 300, 300);

    // 绘制标签文本
    ctx.fillStyle = '#000000';
    ctx.font = 'bold 14px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(label, canvas.width / 2, 320);

    // 返回结果图像的数据URL
    return canvas.toDataURL('image/png');
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  // 搜索区域样式
  .search-area {
    display: flex;
    flex-direction: column;
    background-color: var(--color-bg-2);
    border-radius: 4px;
    padding: 16px 20px;
    position: relative;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .search-form {
      width: 100%;
      margin-bottom: 16px;

      :deep(.arco-form-item) {
        margin-bottom: 0;
      }

      :deep(.arco-form-item-label-col) {
        font-weight: 500;
        color: var(--color-text-1);
      }

      :deep(.arco-input) {
        border-radius: 4px;
        height: 36px;

        &:hover,
        &:focus {
          border-color: var(--color-primary-light-3);
          box-shadow: 0 0 0 2px var(--color-primary-light-4);
        }
      }

      :deep(.arco-select) {
        width: 100%;

        .arco-select-view {
          height: 36px;

          &:hover,
          &:focus {
            border-color: var(--color-primary-light-3);
            box-shadow: 0 0 0 2px var(--color-primary-light-4);
          }
        }
      }
    }

    .operation-area {
      display: flex;
      align-items: center;
      justify-content: center;
      padding-top: 8px;
      margin-top: 8px;
      border-top: 1px dashed var(--color-border-2);

      .search-buttons {
        display: flex;
        gap: 8px;

        .search-btn,
        .reset-btn {
          min-width: 80px;
          height: 36px;
          font-weight: 500;
          border-radius: 4px;
          transition: all 0.2s;
        }

        // .search-btn {
        //   &:hover {
        //     background-color: var(--color-fill-3);
        //     color: var(--color-primary);
        //     border-color: var(--color-primary-light-3);
        //   }
        // }

        .reset-btn {
          &:hover {
            background-color: var(--color-fill-3);
            color: var(--color-primary);
            border-color: var(--color-primary-light-3);
          }
        }
      }

      .add-button {
        .add-btn {
          min-width: 80px;
          height: 36px;
          font-weight: 500;
          border-radius: 4px;
          transition: all 0.2s;
          color: #fff;
          background-color: rgb(var(--success-6));
          border-color: rgb(var(--success-6));

          &:hover {
            background-color: rgb(var(--success-5));
            border-color: rgb(var(--success-5));
          }
        }
      }
    }
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .station-modal {
    :deep(.arco-modal-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;

      .arco-modal-title {
        font-size: 18px;
        font-weight: 500;
      }
    }

    :deep(.arco-modal-body) {
      padding: 20px;
      max-height: 80vh;
      overflow-y: auto;
    }
  }

  .station-form {
    .form-card {
      margin-bottom: 20px;
      border-radius: 4px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

      :deep(.arco-card-header) {
        border-bottom: 1px solid var(--color-border-2);
        padding: 12px 16px;

        .arco-card-header-title {
          font-size: 16px;
          font-weight: 500;
          color: var(--color-text-1);
        }
      }

      :deep(.arco-card-body) {
        padding: 16px;
      }
    }

    // 地理位置卡片中的所有表单项标签向左靠齐
    .location-card {
      :deep(.arco-form) {
        display: grid;
        grid-template-columns: repeat(1, 1fr);
        gap: 16px;

        .arco-form-item {
          margin-bottom: 16px;

          &:nth-last-child(-n + 2) {
            grid-column: 1 / -1;
          }

          .arco-form-item-label-col {
            text-align: left;
            padding-left: 0;
            width: 80px;
            flex: 0 0 80px;
          }

          .arco-form-item-wrapper-col {
            flex: 1;
            width: calc(100% - 80px);
          }
        }
      }
    }

    // 详细地址输入框样式
    .address-item {
      :deep(.arco-form-item-label-col) {
        text-align: left;
        padding-left: 0;
        width: 80px;
        flex: 0 0 80px;
      }

      :deep(.arco-form-item-wrapper-col) {
        flex: 1;
        width: calc(100% - 80px);
      }

      :deep(.arco-input) {
        width: 100%;
      }
    }

    .map-container {
      width: 100%;
      height: 300px;
      margin-bottom: 16px;
      border: 1px solid var(--color-border);
      border-radius: 4px;
      position: relative;
      overflow: hidden;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

      .map-info {
        position: absolute;
        bottom: 0;
        right: 0;
        background: rgba(255, 255, 255, 0.8);
        padding: 8px 12px;
        border-top-left-radius: 4px;
        font-size: 12px;

        p {
          margin: 4px 0;
        }

        .map-tip {
          color: var(--color-text-3);
          font-style: italic;
        }
      }
    }

    .manual-location-input {
      margin-top: 16px;
      padding: 16px;
      border: 1px solid var(--color-border);
      border-radius: 4px;
      background-color: var(--color-fill-2);

      ol {
        margin-top: 8px;
        padding-left: 20px;
      }

      a {
        color: var(--color-primary);
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }
    }

    // 时段设置相关样式
    .time-period-container {
      margin-top: 16px;
      border: 1px solid var(--color-border);
      border-radius: 4px;
      overflow: hidden;
      max-height: 400px;
      overflow-y: auto;

      .time-period-header {
        display: flex;
        padding: 10px 16px;
        background-color: var(--color-fill-2);
        border-bottom: 1px solid var(--color-border);

        .time-period-label {
          font-weight: 500;
          color: var(--color-text-1);

          &:first-child {
            flex: 3;
          }
          &:nth-child(2) {
            flex: 3;
            text-align: center;
          }
          &:last-child {
            flex: 1;
            text-align: center;
          }
        }
      }

      .time-period-item {
        display: flex;
        padding: 10px 16px;
        border-bottom: 1px solid var(--color-border-2);
        align-items: center;

        &:last-child {
          border-bottom: none;
        }

        &:nth-child(even) {
          background-color: var(--color-fill-1);
        }

        .time-period-time {
          flex: 3;
          display: flex;
          align-items: center;

          .time-separator {
            margin: 0 8px;
            color: var(--color-text-3);
          }
        }

        .time-period-type {
          flex: 3;
          text-align: center;

          .time-period-price {
            margin-top: 8px;
            font-size: 12px;
            color: var(--color-text-3);
            max-width: 220px;
            margin: 8px auto 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .time-period-actions {
          flex: 1;
          text-align: center;
        }
      }

      .add-time-period {
        padding: 12px 16px;
        border-top: 1px dashed var(--color-border);
      }
    }

    .form-footer {
      display: flex;
      justify-content: center;
      margin-top: 24px;
      padding: 16px 0;

      .arco-space {
        .arco-btn {
          min-width: 80px;
        }
      }
    }
  }

  .billing-config-list {
    .billing-values-container {
      margin: 16px 0;

      :deep(.arco-btn) {
        min-width: 100px;

        .icon-close {
          opacity: 0;
          transition: opacity 0.2s;
        }

        &:hover {
          .icon-close {
            opacity: 1;
          }
        }
      }
    }

    .custom-value-input {
      display: flex;
      align-items: center;
    }
  }
</style>
